package com.zrrd.yt.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.yt.cart.client.CartFeignClient;
import com.zrrd.yt.common.result.Result;
import com.zrrd.yt.common.util.AuthContextHolder;
import com.zrrd.yt.model.cart.CartInfo;
import com.zrrd.yt.model.enums.OrderStatus;
import com.zrrd.yt.model.order.OrderDetail;
import com.zrrd.yt.model.order.OrderInfo;
import com.zrrd.yt.model.user.UserAddress;
import com.zrrd.yt.order.mapper.OrderDetailMapper;
import com.zrrd.yt.order.service.OrderService;
import com.zrrd.yt.product.client.ProductFeignClient;
import com.zrrd.yt.user.client.UserFeignClient;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HongyueYang
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private OrderDetailMapper detailMapper;

    //订单结算
    @GetMapping("/auth/trade")
    public Result<Map> trade(HttpServletRequest request){
        System.out.println("youtao");
        //获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //创建最终返回的Map集合
        Map<String,Object> map = new HashMap<>();
        //获取用户地址信息
        List<UserAddress> userAddresses = userFeignClient.findUserAddressByUserId(userId);
        System.out.println("获取的地址信息====>"+userAddresses);
        //获取用户选中的购物车数据信息
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        System.out.println("获取的选中商品====>"+cartCheckedList);
        //创建订单明细集合
        List<OrderDetail> detailList = new ArrayList<>();
        //将购物车的数据转换后存入订单明细集合
        for (CartInfo cartInfo : cartCheckedList) {
            OrderDetail detail = new OrderDetail();
            detail.setSkuId(cartInfo.getSkuId());
            detail.setSkuName(cartInfo.getSkuName());
            detail.setSkuNum(cartInfo.getSkuNum());
            detail.setOrderPrice(cartInfo.getSkuPrice());
            detailList.add(detail);
        }
        //计算订单总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailList);
        orderInfo.sumTotalAmount();

        //获取流水号
        String tradeNo = orderService.getTradeNo(userId);

        //存入Map集合
        map.put("userAddressList",userAddresses);
        map.put("detailArrayList",detailList);
        map.put("totalNum",detailList.size());
        map.put("totalAmount",orderInfo.getTotalAmount());
        map.put("tradeNo",tradeNo);
        //返回
        return Result.ok(map);
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //设置用户ID
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //根据请求对象获取流水号参数
        String tradeNo = request.getParameter("tradeNo");
        //校验流水号
        boolean checkTradeNo = orderService.checkTradeNo(userId, tradeNo);
        if (!checkTradeNo) {
            return Result.fail().message("不能提交重复的订单");
        }
        //删除流水号
        orderService.deleteTradeNo(userId);
        //获取订单明细
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            //校验库存
            boolean checkStock = orderService.checkStock(detail.getSkuId(), detail.getSkuNum());
            if (!checkStock) {
                return Result.fail().message(detail.getSkuName() + "库存不足");
            }
            //校验价格
            BigDecimal skuPrice = productFeignClient.getSkuPrice(detail.getSkuId());
            System.out.println("获取的最新价格====>"+skuPrice);
            System.out.println("订单明细的商品价格====>"+detail.getOrderPrice());
            if(detail.getOrderPrice().compareTo(skuPrice) != 0){
                //重新更新最新价格
                cartFeignClient.loadCartData(userId);
                return Result.fail().message(detail.getSkuName() + "价格有变动，请刷新页面重试");
            }
        }
        //调用业务层提交订单
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //返回结果
        return Result.ok(orderId);
    }

    //获取订单信息
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable("orderId") Long orderId) {
        return orderService.getOrderInfo(orderId);
    }

    //分页查询我的订单
    @GetMapping("/auth/{page}/{limit}")
    public Result<Page> getOrderList(@PathVariable("page") Long page, @PathVariable("limit") Long limit, HttpServletRequest request){

        //获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //分页查询订单
        Page<OrderInfo> pageInfo = new Page<>(page,limit);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
       wrapper.orderByDesc("create_time");
        orderService.page(pageInfo,wrapper);
        //设置订单明细
        for (OrderInfo orderInfo : pageInfo.getRecords()) {
            //获取当前订单状态
            String orderStatus = orderInfo.getOrderStatus();
            //设置当前订单状态名称
            orderInfo.setOrderStatusName(OrderStatus.getStatusNameByStatus(orderStatus));
            //获取订单明细
            QueryWrapper<OrderDetail> detailWrapper = new QueryWrapper<>();
            detailWrapper.eq("order_id",orderInfo.getId());
            List<OrderDetail> detailList =detailMapper.selectList(detailWrapper);
            orderInfo.setOrderDetailList(detailList);
        }
        return Result.ok(pageInfo);
    }

    //提交秒杀订单
    @PostMapping("/inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        //获取订单ID
        Long ID = orderService.saveOrderInfo(orderInfo);
        //返回订单ID
        return ID;
    }

}
